---
- name: Установка и настройка nginx
  hosts: nginx-balancer
  become: yes
  gather_facts: no

  tasks:

    - name: Установка nginx
      apt:
        name: nginx
        state: latest
        update_cache: yes
        autoclean: yes
        autoremove: yes

    - name: Ensure nginx config file exists
      copy:
        content: |
          upstream vault_servers {
            {% for host in upstreams %}
            server {{ host }}:8200 max_fails=3 fail_timeout=2s;
            {% endfor %}
          }

          server {
            listen 9000 ssl http2 default_server;
            listen [::]:9000 ssl http2 default_server;

            ssl_certificate /etc/ssl/vault/vault.crt;
            ssl_certificate_key /etc/ssl/vault/vault.key;

            ssl_protocols TLSv1.3;
            ssl_prefer_server_ciphers on;
            ssl_ciphers "EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH";
            ssl_ecdh_curve secp384r1;
            ssl_session_cache shared:SSL:10m;
            ssl_session_tickets off;
            ssl_stapling on;
            ssl_stapling_verify on;
            resolver 8.8.8.8 8.8.4.4 valid=300s;
            resolver_timeout 5s;
            add_header Strict-Transport-Security "max-age=63072000; includeSubdomains; preload";
            add_header X-Frame-Options "SAMEORIGIN";
            add_header X-Content-Type-Options nosniff;
        
            location / {
              proxy_set_header Host $http_host;
              proxy_set_header X-Real-IP $remote_addr;
              proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
              proxy_set_header X-Forwarded-Proto $scheme;
              proxy_pass {{ schema }}://vault_servers;
            }
          
          }

        dest: "/etc/nginx/sites-available/default"
        owner: root
        group: root
        mode: '0644'

    - name: Проверка синтаксиса конфигурации Nginx
      command: nginx -t
      register: nginx_check
      failed_when: "nginx_check.rc != 0"

    - name: Перезагружаем Nginx
      service:
        name: nginx
        state: restarted
      when: "nginx_check.rc == 0"
